﻿using System;

using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;

namespace Silvermoon.OpenGL.Native
{
    [StructLayout(LayoutKind.Explicit)]
    public struct GlColor
    {
        [FieldOffset(0)]
        public int Value;

        [FieldOffset(0)]
        public byte R;

        [FieldOffset(1)]
        public byte G;

        [FieldOffset(2)]
        public byte B;

        [FieldOffset(3)]
        public byte A;

        public Color SwapRB()
        {
            byte b = B;
            B = R;
            R = b;
            return this;
        }

        public static GlColor FromArgb(byte a, byte r, byte g, byte b)
        {
            GlColor color = new GlColor();
            color.A = a;
            color.R=r;
            color.G=g;
            color.B=b;
            return color;
        }

        public GlColor(byte a, byte r, byte g, byte b)
        {
            Value = 0;
            A = a;
            R = r;
            G = g;
            B = b;

        }

        public static implicit operator GlColor(Color color)
        {
            return new GlColor { Value = color.ToArgb() };
        }

        public static implicit operator GlColor(int color)
        {
            return new GlColor { Value = color };
        }

        public static implicit operator Color(GlColor color)
        {
            return Color.FromArgb(color.Value);
        }

        public static bool operator ==(GlColor color, int value)
        {
            return color.Value == value;
        }

        public static bool operator !=(GlColor color, int value)
        {
            return color.Value != value;
        }

        public static bool operator ==(GlColor glColor, Color color)
        {
            return glColor.Value == color.ToArgb();
        }

        public static bool operator !=(GlColor glColor, Color color)
        {
            return glColor.Value != color.ToArgb();
        }

        public override int GetHashCode()
        {
            return Value;
        }

        public override bool Equals(object obj)
        {
            if (!(obj is GlColor)) return false;
            GlColor color = (GlColor)obj;
            return color.Value == Value;
        }

        public static GlColor FromColor(Color color)
        {
            GlColor c = color;
            c.SwapRB();
            return c;
        }

        public short ToBGRA5551()
        {
            int a = A>8 ? 1:0;
            int v = ((B / 8) << 11) | ((G / 8) << 6) | ((R / 8) << 1) | a;
            return (short)v;
        }

        public static short FromRGB555ToBGRA5551(short value)
        {
            return (short)((value << 1) | 1);
        }
    }
}
